from flask import request, g
from flask_restful import abort

from apps.models.user_model import User
from exts import redis_cache


def check_user():
    token = request.args.get('token')
    if not token:
        abort(400, msg='请登录')
    user_id = redis_cache.get(token)

    if not user_id:
        abort(400, msg='无效令牌')
    user = User.query.get(user_id)
    if not user:
        abort(400, msg='此用户已被注销')
    # g对象  本次请求的全局对象
    g.user = user


def login_required(func):
    def wrapper(*args, **kwargs):
        check_user()
        return func(*args, **kwargs)

    return wrapper
